var div = document.getElementById('content_div');
var title = document.getElementById('gadget_title');

function stateUpdated() {
	try {
		var options = getData('options');
		var votedUsers = getData('votes');
  	
    	if(!options) {
      		div.innerHTML = 'There are no options! Create some options.';
    	}
    	else {
    		var alreadyVoted = hasVoted();
    		var hasFullRights = isHost();
    		
    		var contents = '<table>';
    		contents += '<thead><tr><td>Option</td><td>Votes</td>';
    		
    		if (!alreadyVoted) {
    			contents += '<td></td>';
    		}
    		if (hasFullRights) {
    			contents += '<td></td>';
    		}
    		contents += '</tr></thead>';

    		for (optionKey in options) {
    			var escapedOptionKey = removeQuotes(optionKey);
    			contents += '<tr>';
    			contents += '<td>' + optionKey + '</td>';
    			contents += '<td>' + options[optionKey].votes + '</td>';
    			if (!alreadyVoted) {
    				contents += '<td><input type="button" value="Vote!" id="bVote" onClick="vote(\'' + escapedOptionKey + '\')"></td>';
    			}
    			if (hasFullRights) {
    				contents += '<td><input type="button" value="Remove this Option" id="bRemoveOption" onClick="removeOption(\'' + escapedOptionKey + '\')"></td>';
    			}
    			contents += '</tr>';
    		}
    		contents += '</table>';
    		
    		if (alreadyVoted) {
    			contents += '<input type="button" value="Change Your Vote" id="bCancelVote" onClick="cancelVote()">';
    		}
    		
    		contents += '<div class="list-header">Already voted</div>';
    		contents += '<ul>'
    		for (userId in votedUsers) {
    			var user = wave.getParticipantById(userId);
    			contents += '<li>' + user.getDisplayName() + '</li>';
    		}
    		contents += '</ul>'
    		
      		div.innerHTML = contents;
    		title.innerHTML = 'Secret Poll';  		
    		
      		gadgets.window.adjustHeight();
    	}
	}
	catch (e) {
		alert('Error in stateUpdated()\n' + e);
	}
}

// Note: registration must happen after function is defined.
function init() {
	try {
    	if (wave && wave.isInWaveContainer()) {
      		wave.setStateCallback(stateUpdated);
    	}
	}
	catch (e) {
		alert('Error in init()\n' + e);
	}
}
gadgets.util.registerOnLoadHandler(init);

function removeOption(escapedOptionKey) {
	try {
		var optionKey = readdQuotes(escapedOptionKey);
		
		// Remove the option
		var options = getData('options');
		delete options[optionKey];
		
		// Remove any users who voted for this option so they can vote again
		var votedUsers = getData('votes');
		for (votedUser in votedUsers) {
			if (votedUsers[votedUser] == optionKey) {
				delete votedUsers[votedUser];
			}
		}
		
		submitData({
			'options': encode(options),
			'votes': encode(votedUsers)
		});
	}
	catch (e) {
		alert('Error in removeOption()\n' + e);
	}
}

function vote(escapedOptionKey) {
	try {
		var optionKey = readdQuotes(escapedOptionKey);
		
		var options = getData('options');
		options[optionKey].votes = parseInt(options[optionKey].votes) + 1;
		
		var currentUserId = wave.getViewer().getId();
		var votedUsers = getData('votes');
		votedUsers[currentUserId] = optionKey;
		
		submitData({
			'options': encode(options),
			'votes': encode(votedUsers)
		});
	}
	catch (e) {
		alert('Error in vote()\n' + e);
	}
}

function cancelVote() {
	try {
		var currentUserId = wave.getViewer().getId();
	
		var votedUsers = getData('votes');
		var votedForName = votedUsers[currentUserId];
		
		var options = getData('options');
		var votedForOption = options[votedForName];
		
		if (votedForOption) {
			votedForOption.votes = votedForOption.votes - 1;
			delete votedUsers[currentUserId];
		}
		else {
			delete votedUsers[currentUserId];
		}
		
		submitData({
			'options': encode(options),
			'votes': encode(votedUsers)
		});
	}
	catch (e) {
		alert('Error in vote()\n' + e);
	}
}

function addOption() {
	try {
		var textOptionName = document.getElementById('textOptionName');
		var options = getData('options');
		var optionName = textOptionName.value;
		
		if (options[optionName]) {
			alert('That option already exists.');
		}
		else if (optionName == '') {
			alert('Enter a option name.');
		}
		else {
			options[optionName] = {'votes': '0'};
			submitData({'options': encode(options)});
			textOptionName.value = '';
		}
	}
	catch (e) {
		alert('Error in addOption()\n' + e);
	}		 
}

function isHost() {
	var currentUserId = wave.getViewer().getId();
	var hostUserId = wave.getHost().getId();
	return currentUserId == hostUserId;
}

function hasVoted() {
	var currentUserId = wave.getViewer().getId();
	var votedUsers = getData('votes');
	
	if (votedUsers[currentUserId]) {
		return true;
	}
	else {
		return false;
	}
}	

function getData(key) {
	var dataJson = wave.getState().get(key, "{}");
	return gadgets.json.parse(dataJson);
}

function encode(nonJson) {
	return gadgets.json.stringify(nonJson);
}

function submitData(dict) {
	wave.getState().submitDelta(dict);
}

function removeQuotes(s) {
	return s.replace(/\'/g, "__s__").replace(/\"/g, "__d__");
}

function readdQuotes(s) {
	return s.replace(/__s__/g, "\'").replace(/__d__/g, "\"");
}